xquery version "1.0";

declare namespace util="http://exist-db.org/xquery/util";
declare namespace dc="http://purl.org/dc/elements/1.1/";
declare namespace request="http://exist-db.org/xquery/request";
declare namespace session="http://exist-db.org/xquery/session";

declare option exist:serialize "method=xhtml media-type=text/xml";

declare function local:genresByArtistId(){
	for $artist in doc("Test1/Artists.xml")//artist
	let $artistId := request:get-parameter("artistId", ())
	where $artist/@id = $artistId
	return data($artist/genres/genre[last()])
};

declare function local:rate($r,$rc) {
	if ($rc = 0) then 0
	else $r
};

element { "albums" }{ 
	fn:subsequence(
	for $artist in doc("Test1/Artists.xml")//artist
	let $artistId := request:get-parameter("artistId", ())
	let $genres := local:genresByArtistId()
	where $artist/genres/genre = $genres and
	      $artist/@id != $artistId
	order by number(local:rate(data($artist/rating),data($artist/rating-count))) descending
	return $artist
	,1, xs:integer(request:get-parameter("count", ())))
}
